/// 值类型转换，可空返回
typedef TransformationReturnNullable<S, T> = T? Function(S value);

extension CompactMap<E> on List<E> {
  /// 列表值类型转换，会过滤 null 值。
  ///
  /// ```dart
  /// final List<String> strings = ['1', 's2', '3'];
  /// final List<int> ints = strings.compactMap(
  ///   (e) => int.tryParse(e),
  /// ); // [1, 3]
  /// ```
  List<T> compactMap<T>(
    TransformationReturnNullable<E, T> transformation,
  ) {
    final list = <T>[];
    for (E e in this) {
      final t = transformation(e);
      if (t != null) {
        list.add(t);
      }
    }
    return list;
  }

  /// 将列表转换为 int 数组。不能转换的将被过滤。
  List<int> toInts() => compactMap((value) => int.tryParse(value.toString()));
}

extension JsonList on List {
  static List<String>? stringsFromJson(dynamic json) {
    if (json is! List) {
      return null;
    }

    if (json is List<String>) {
      return json;
    }

    final list = <String>[];

    for (dynamic item in json) {
      if (item is String) {
        list.add(item);
      } else {
        list.add(item.toString());
      }
    }

    return list;
  }

  static List<int>? intsFromJson(dynamic json) {
    if (json is! List) {
      return null;
    }

    final list = <int>[];

    for (dynamic item in json) {
      if (item is num) {
        list.add(item.toInt());
      } else if (item is String) {
        list.add(int.tryParse(item) ?? 0);
      }
    }

    return list;
  }
}
